package learn.spring.blog.backend.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

/***
 * 重定向获取token controller
 */
@Slf4j
@Controller
@RequestMapping("")
public class CodeRedirectController {

  @Autowired
  private RestTemplate restTemplate;

  @GetMapping("/code-redirect")
  public String helloCodeRedirect(Model model, @RequestParam String code) {
    log.error("========================code {} ", code);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//    todo 参数硬编码，后续改为挂载secret卷
    headers.add("Authorization", "Basic bXktY2xpZW50Om15LXNlY3JldA==");

    MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
    para.add("code", code);
    para.add("grant_type", "authorization_code");
    para.add("redirect_uri", "http://chins-blog.me/code-redirect");
    HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(para, headers);
    log.error("---------------------------------para -{} ", para);
    ResponseEntity<String> resp = restTemplate.exchange ("http://learn-auth:8800/oauth2/token",
        HttpMethod.POST,
        requestEntity,
        String.class);
    log.error("----------------------------------");
    log.error("token {} ", resp.getStatusCode());
    log.error("token {} ", resp.getBody());
    model.addAttribute("token", resp.getBody());
    return "loading";
  }

}
